/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.context.impl;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.dailydev.wave.robot.Robot;
import org.dailydev.wave.robot.RobotException;
import org.dailydev.wave.robot.context.IWaveletContext;
import org.dailydev.wave.robot.serializer.ISerializer;
import org.dailydev.wave.robot.serializer.Serializer;

import com.google.wave.api.Wavelet;

/**
 * @author Roman Bosak, DailyDev.org
 */
public class WaveletContext extends HashMapContext implements IWaveletContext {

    /**
     * {@link Robot}'s logger
     */
    private static Logger log = Logger.getLogger(WaveletContext.class.getName());

    /**
     * 
     */
    protected static final String WAVELET_CONTEXT = "WAVELET_CONTEXT";

    /**
     * 
     */
    private final Wavelet wavelet;

    /**
     * Robot specific ID of Wavelet's context. It is used as a name of Wavelet's
     * data document containing robot's context. It consist of robot's address +
     * {@link WaveletContext#WAVELET_CONTEXT}.
     */
    protected final String WAVELET_CONTEXT_ID;

    /**
     * 
     */
    private final ISerializer<Map<String, Object>> serializer;

    /**
     * @param wavelet
     * @param robotAddress
     */
    public WaveletContext(Wavelet wavelet, String robotAddress) {
        this.wavelet = wavelet;
        this.WAVELET_CONTEXT_ID = robotAddress + "+" + WAVELET_CONTEXT;

        serializer = new Serializer<Map<String, Object>>();

        String dataDocument = this.wavelet.getDataDocument(WAVELET_CONTEXT_ID);
        if (dataDocument != null && !dataDocument.isEmpty()) {
            try {
                Map<String, Object> parsed = serializer.deserialize(dataDocument);
                super.putAll(parsed);
            } catch (RobotException e) {
                log.log(Level.WARNING,
                        "Deserialization of Wavelet's context failed.\nData document: \n" + dataDocument, e);
            }
        }
    }

    /** {@inheritDoc} */
    @Override
    public void clear() {
        super.clear();
        updateDataDocument();
    }

    /** {@inheritDoc} */
    @Override
    public Object put(String key, Object value) {
        Object result = super.put(key, value);
        updateDataDocument();
        return result;
    }

    /** {@inheritDoc} */
    @Override
    public void putAll(Map<? extends String, ? extends Object> m) {
        super.putAll(m);
        updateDataDocument();
    }

    /** {@inheritDoc} */
    @Override
    public Object remove(Object key) {
        Object result = super.remove(key);
        updateDataDocument();
        return result;
    }

    /**
     * 
     */
    protected void updateDataDocument() {
        try {
            Map<String, Object> context = getContextMap();
            if (context.isEmpty()) {
                if (wavelet.hasDataDocument(WAVELET_CONTEXT_ID)) {
                    wavelet.setDataDocument(WAVELET_CONTEXT_ID, "");
                }
            } else {
                String json = serializer.serialize(context);
                wavelet.setDataDocument(WAVELET_CONTEXT_ID, json);
            }
        } catch (RobotException e) {
            log.log(Level.WARNING, "Serialization of Wavelet's context failed.", e);
        }
    }

}
